package com.kmdd.xtds.ui

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.kmdd.xtds.R
import com.kmdd.xtds.adapterOf
import com.kmdd.xtds.configs.PrefsManager
import com.kmdd.xtds.databinding.FragmentSecondBinding
import com.kmdd.xtds.databinding.ItemBloodRecordBinding
import com.kmdd.xtds.listAdapterOf
import com.kmdd.xtds.room.BloodPressureDatabase
import com.kmdd.xtds.room.BloodSugar
import com.kmdd.xtds.util.TimeUtil
import com.kmdd.xtds.util.TimeUtils
import com.kmdd.xtds.util.launch
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.withContext

/**
 * A simple [Fragment] subclass as the second destination in the navigation.
 */
class SecondFragment : Fragment() {

    private var _binding: FragmentSecondBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!


    private val mAdapter = listAdapterOf(object : DiffUtil.ItemCallback<BloodSugar>() {

        override fun areItemsTheSame(
            oldItem: BloodSugar, newItem: BloodSugar
        ): Boolean {
            return false
        }

        override fun areContentsTheSame(
            oldItem: BloodSugar, newItem: BloodSugar
        ): Boolean {
            return false
        }
    }, viewCreator = ItemBloodRecordBinding::inflate, viewHolderBinder = { holder, item, pos ->
        holder.binding.tvTitle.text = "血糖" + item.bloodValue + "mmol/L"
        holder.binding.tvRecord.text =
            "记录时间：${TimeUtils.millis2String(item.timeStamp, "yyyy-MM-dd HH:mm:ss")}"
        holder.binding.tvStatus.text = if ((item.bloodValue.toDoubleOrNull() ?: 0.0) < 3.9) {
            "偏低"
        } else if ((item.bloodValue.toDoubleOrNull() ?: 0.0) > 6.1) {
            "偏高"
        } else {
            "正常"
        }
        holder.binding.tvStatus.setTextColor(
            if ((item.bloodValue.toDoubleOrNull() ?: 0.0) < 3.9) {
                requireContext().resources.getColor(R.color.color_007AFF)
            } else if ((item.bloodValue.toDoubleOrNull() ?: 0.0) > 6.1) {
                requireContext().resources.getColor(R.color.color_FF9500)
            } else {
                requireContext().resources.getColor(R.color.color_00C7BE)
            }
        )
    })

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {

        _binding = FragmentSecondBinding.inflate(inflater, container, false)
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initList()
        binding.tvRecord.setOnClickListener { BloodRecordAddActivity.start(requireContext()) }
        binding.ivAdd.setOnClickListener { BloodRecordAddActivity.start(requireContext()) }
        launch {
            PrefsManager.bloodRecordFlow.collectLatest {
                Log.d("PrefsManager", "数据映射:${it}")
                binding.tvBlood.text = it.bloodValue
                binding.tvHeight.text = it.bloodHeight
                binding.tvWeight.text = it.bloodWeight
            }
        }
    }

    private fun initList() {
        binding.recycler.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = mAdapter
        }
        launch {
            //查询数据库
            withContext(Dispatchers.IO) {
                BloodPressureDatabase.getInstance(context!!)?.bloodSugarDao()?.queryList()
                    ?.collectLatest {
                        mAdapter.submitList(it)
                    }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}